<template>
  <div class="template-container">
    <!-- 模板选择页面 -->
    <div v-if="!selectedTemplate" class="template-selection">
      <div class="template-header">
        <h2>简历模板</h2>
        <p>选择您喜欢的简历模板，开始制作专业简历</p>
      </div>

      <!-- 简历模板选择部分 -->
      <div class="template-list">
        <div
          v-for="tpl in templates"
          :key="tpl.id"
          class="template-card"
          @mouseenter="tpl.hover = true"
          @mouseleave="tpl.hover = false"
        >
          <div class="template-img-wrapper">
            <img :src="tpl.preview_img" class="template-img" />
            <transition name="fade">
              <button
                v-if="tpl.hover"
                class="template-hover-btn"
                @click="selectTemplate(tpl)"
              >
                立即免费制作
              </button>
            </transition>
          </div>
          <div class="template-info">
            <h3 class="template-name">{{ tpl.name }}</h3>
            <p class="template-desc">{{ tpl.description }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- 简历编辑页面 -->
    <div v-else class="resume-editor">
      <div class="editor-header">
        <button class="back-btn" @click="backToTemplates">
          <i class="back-icon">←</i>
          返回模板选择
        </button>
        <h2>{{ selectedTemplate.name }} - 简历编辑</h2>
      </div>

      <div class="editor-content">
        <!-- 基础信息表单 -->
        <form class="resume-form" @submit.prevent="saveResume">
          <h3>基础信息</h3>
          <input v-model="resume.name" placeholder="姓名" />
          <input v-model="resume.gender" placeholder="性别" />
          <input v-model="resume.birthday" type="date" placeholder="出生日期" />
          <input v-model="resume.phone" placeholder="电话" />
          <input v-model="resume.email" placeholder="邮箱" />
          <input v-model="resume.city" placeholder="城市" />
          <textarea v-model="resume.self_intro" placeholder="自我介绍"></textarea>

          <!-- 教育经历 -->
          <h3>教育经历</h3>
          <div v-for="(edu, idx) in resume.educations" :key="idx" class="edu-block">
            <input v-model="edu.school" placeholder="学校" />
            <input v-model="edu.degree" placeholder="学历" />
            <input v-model="edu.major" placeholder="专业" />
            <input v-model="edu.start_date" type="date" placeholder="开始时间" />
            <input v-model="edu.end_date" type="date" placeholder="结束时间" />
            <textarea v-model="edu.desc" placeholder="描述"></textarea>
            <button class="del-btn" @click.prevent="removeEducation(idx)">删除</button>
          </div>
          <button class="add-btn" @click.prevent="addEducation">添加教育经历</button>

          <!-- 工作经历 -->
          <h3>工作经历</h3>
          <div v-for="(work, idx) in resume.work_experiences" :key="idx" class="work-block">
            <input v-model="work.company" placeholder="公司" />
            <input v-model="work.position" placeholder="职位" />
            <input v-model="work.start_date" type="date" placeholder="开始时间" />
            <input v-model="work.end_date" type="date" placeholder="结束时间" />
            <textarea v-model="work.desc" placeholder="工作内容"></textarea>
            <button class="del-btn" @click.prevent="removeWork(idx)">删除</button>
          </div>
          <button class="add-btn" @click.prevent="addWork">添加工作经历</button>

          <div class="form-btns">
            <button type="submit" class="save-btn">保存</button>
            <button type="button" class="export-btn" @click="exportResume">导出简历</button>
          </div>
        </form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import request from '@/utils/request'

const templates = ref([])
const selectedTemplate = ref(null)
const resume = ref({
  name: '',
  gender: '',
  birthday: '',
  phone: '',
  email: '',
  city: '',
  self_intro: '',
  educations: [],
  work_experiences: []
})

const fetchTemplates = async () => {
  try {
    const res = await request.get('resume/templates/')
    templates.value = res.data.map(tpl => ({ ...tpl, hover: false }))
  } catch (error) {
    console.error('获取模板失败:', error)
    // 如果API不可用，使用默认模板数据
    templates.value = [
      {
        id: 1,
        name: '经典简约模板',
        description: '适合各行业求职者，突出个人能力',
        preview_img: 'https://via.placeholder.com/320x440/00b488/ffffff?text=经典模板',
        hover: false
      },
      {
        id: 2,
        name: '创意设计模板',
        description: '适合设计、创意类职位',
        preview_img: 'https://via.placeholder.com/320x440/ff6b6b/ffffff?text=创意模板',
        hover: false
      },
      {
        id: 3,
        name: '商务专业模板',
        description: '适合管理、商务类职位',
        preview_img: 'https://via.placeholder.com/320x440/4ecdc4/ffffff?text=商务模板',
        hover: false
      }
    ]
  }
}

const selectTemplate = (tpl) => {
  selectedTemplate.value = tpl
  // 根据模板预设一些基础信息
  resume.value.name = tpl.name || ''
  resume.value.gender = tpl.gender || ''
  resume.value.city = tpl.city || ''
}

const backToTemplates = () => {
  selectedTemplate.value = null
  // 重置简历数据
  resume.value = {
    name: '',
    gender: '',
    birthday: '',
    phone: '',
    email: '',
    city: '',
    self_intro: '',
    educations: [],
    work_experiences: []
  }
}

const saveResume = async () => {
  try {
    await request.post('resume/resume/', resume.value)
    alert('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    alert('保存失败，请重试')
  }
}

const exportResume = () => {
  // 创建打印样式
  const printStyle = `
    <style>
      @media print {
        body { margin: 0; padding: 20px; }
        .resume-print { 
          font-family: Arial, sans-serif; 
          max-width: 800px; 
          margin: 0 auto;
          line-height: 1.6;
        }
        .resume-header { 
          text-align: center; 
          border-bottom: 2px solid #333; 
          padding-bottom: 20px; 
          margin-bottom: 30px;
        }
        .resume-section { 
          margin-bottom: 25px; 
        }
        .resume-section h3 { 
          color: #00b488; 
          border-bottom: 1px solid #eee; 
          padding-bottom: 5px;
        }
        .education-item, .work-item { 
          margin-bottom: 15px; 
          padding: 10px; 
          background: #f9f9f9; 
          border-radius: 5px;
        }
        .no-print { display: none !important; }
      }
    </style>
  `

  // 创建简历内容
  const resumeContent = `
    <div class="resume-print">
      <div class="resume-header">
        <h1>${resume.value.name || '姓名'}</h1>
        <p>${resume.value.phone || '电话'} | ${resume.value.email || '邮箱'} | ${resume.value.city || '城市'}</p>
        <p>${resume.value.self_intro || '自我介绍'}</p>
      </div>

      <div class="resume-section">
        <h3>教育经历</h3>
        ${resume.value.educations.map(edu => `
          <div class="education-item">
            <h4>${edu.school || '学校'}</h4>
            <p>${edu.degree || '学历'} - ${edu.major || '专业'}</p>
            <p>${edu.start_date || '开始时间'} - ${edu.end_date || '结束时间'}</p>
            <p>${edu.desc || '描述'}</p>
          </div>
        `).join('')}
      </div>

      <div class="resume-section">
        <h3>工作经历</h3>
        ${resume.value.work_experiences.map(work => `
          <div class="work-item">
            <h4>${work.company || '公司'}</h4>
            <p>${work.position || '职位'}</p>
            <p>${work.start_date || '开始时间'} - ${work.end_date || '结束时间'}</p>
            <p>${work.desc || '工作内容'}</p>
          </div>
        `).join('')}
      </div>
    </div>
  `

  // 打开新窗口并打印
  const printWindow = window.open('', '_blank')
  printWindow.document.write(printStyle + resumeContent)
  printWindow.document.close()
  printWindow.focus()
  printWindow.print()
}

const addEducation = () => {
  resume.value.educations.push({
    school: '', degree: '', major: '', start_date: '', end_date: '', desc: ''
  })
}

const removeEducation = (idx) => {
  resume.value.educations.splice(idx, 1)
}

const addWork = () => {
  resume.value.work_experiences.push({
    company: '', position: '', start_date: '', end_date: '', desc: ''
  })
}

const removeWork = (idx) => {
  resume.value.work_experiences.splice(idx, 1)
}

onMounted(() => {
  fetchTemplates()
})
</script>

<style scoped>
.template-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  background: #f7f8fa;
  min-height: 100vh;
  padding: 40px 20px;
}

.template-selection {
  width: 100%;
  max-width: 1200px;
}

.template-header {
  text-align: center;
  margin-bottom: 40px;
}

.template-header h2 {
  color: #333;
  font-size: 28px;
  margin-bottom: 8px;
}

.template-header p {
  color: #666;
  font-size: 16px;
}

.template-list {
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
  justify-content: center;
}

.template-card {
  position: relative;
  width: 320px;
  height: 500px;
  border-radius: 14px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0,0,0,0.10);
  background: #fff;
  transition: box-shadow 0.2s;
  cursor: pointer;
  display: flex;
  flex-direction: column;
}

.template-card:hover {
  box-shadow: 0 6px 24px rgba(0,180,136,0.18);
}

.template-img-wrapper {
  width: 100%;
  height: 440px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.template-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: filter 0.2s;
}

.template-card:hover .template-img {
  filter: brightness(0.7);
}

.template-hover-btn {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: rgba(0, 180, 136, 0.95);
  color: #fff;
  font-size: 18px;
  font-weight: bold;
  border: none;
  border-radius: 8px;
  padding: 16px 32px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0,0,0,0.10);
  opacity: 0.98;
  transition: background 0.2s, opacity 0.2s;
}

.template-hover-btn:hover {
  background: #009e6d;
  opacity: 1;
}

.template-info {
  padding: 16px;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.template-name {
  font-size: 18px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.template-desc {
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

/* 编辑器样式 */
.resume-editor {
  width: 100%;
  max-width: 800px;
}

.editor-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
  gap: 20px;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  background: #f5f7fa;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 8px 16px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.back-btn:hover {
  background: #e9ecef;
  color: #333;
}

.back-icon {
  font-size: 16px;
  font-weight: bold;
}

.editor-header h2 {
  color: #333;
  font-size: 24px;
  margin: 0;
}

.editor-content {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(0,0,0,0.08);
  padding: 32px 40px;
}

.resume-form h3 {
  margin-top: 18px;
  margin-bottom: 10px;
  color: #00b488;
}

.resume-form input,
.resume-form textarea {
  width: 100%;
  margin-bottom: 10px;
  padding: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 15px;
  background: #fafbfc;
  transition: border 0.2s;
}

.resume-form input:focus,
.resume-form textarea:focus {
  border: 1.5px solid #00b488;
  outline: none;
}

.add-btn, .del-btn {
  background: #f5f7fa;
  color: #00b488;
  border: 1px solid #00b488;
  border-radius: 4px;
  padding: 4px 12px;
  margin-bottom: 10px;
  margin-right: 8px;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s, color 0.2s;
}

.add-btn:hover, .del-btn:hover {
  background: #00b488;
  color: #fff;
}

.form-btns {
  display: flex;
  gap: 16px;
  margin-top: 18px;
}

.save-btn, .export-btn {
  background: #00b488;
  color: #fff;
  border: none;
  border-radius: 4px;
  padding: 8px 24px;
  font-size: 16px;
  cursor: pointer;
  transition: background 0.2s;
}

.save-btn:hover, .export-btn:hover {
  background: #009e6d;
}

.edu-block, .work-block {
  border: 1px solid #eee;
  padding: 12px;
  margin-bottom: 12px;
  border-radius: 8px;
  background: #fafbfc;
}

.fade-enter-active, .fade-leave-active {
  transition: opacity 0.2s;
}

.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
</style>
